/**
 * 
 */
package org.dragonfire.util.token;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Scanner;

import org.dragonfire.ti.TIFile;

/**
 * @author Darth Android
 * @date Oct 5, 2007
 */
public class TokenOutputStream extends OutputStream {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		TokenOutputStream tos = new TokenOutputStream(TIFile.getTokenTable(TIFile.CALC_8X), System.out);
		PrintStream ps = new PrintStream(tos);
		System.out.println("Enter a token:");
		String line = "";
		while (!line.equals("halt")) {
			line = in.nextLine();
			ps.println(line);
			ps.flush();
		}
	}

	private TokenTable table;
	private OutputStream stream;
	private StringBuffer buffer = new StringBuffer();

	/**
	 * 
	 */
	public TokenOutputStream(TokenTable table, OutputStream outStream) {
		if (outStream == null)
			throw new NullPointerException("outStream may not be null");
		this.table = table;
		stream = outStream;
	}

	@Override
	public void write(int b) throws IOException {
		buffer.append((char) b);
	}

	public void flush() throws IOException {
		Token[] ts = table.readTokens(buffer.toString());
		for (Token t : ts) {
			if (t == Token.UNDEFINED) {
				continue;
			}
			for (Byte b : t.getBytes()) {
				stream.write(b);
			}
		}
		super.flush();
	}
}
